package com;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.SocketChannel;
import java.nio.channels.WritableByteChannel;

public class ChargenClient {

    private final static int DEFAULT_PORT = 19;

    private final static int BUFFER_SIZE = 74;

    private static String host;

    private static int port;

    public static void main(String[] args) {

        if(args.length == 0){
            System.out.println("Usage: java ChargenClient host [port]");
            return;
        }

        host = args[0];

        if(args.length > 1){
            port = Integer.parseInt(args[1]);
        }else{
            port = DEFAULT_PORT;
        }

        try {
            SocketAddress addr = new InetSocketAddress(host,port);

            SocketChannel channel = SocketChannel.open(addr);

            ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);

            WritableByteChannel out = Channels.newChannel(System.out);

            //非阻塞模式
            channel.configureBlocking(false);

            while (true){

                //此处可以处理其他事情

                int n = channel.read(buffer);

                if(n > 0){

                    buffer.flip();

                    out.write(buffer);

                    buffer.clear();

                }else if(n == -1) break;

            }

            /*
            //阻塞模式
            while ((channel.read(buffer)) != -1){

                buffer.flip();

                out.write(buffer);

                buffer.clear();

            }*/

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
